import request from '../../utils/request'
Page({
  data: {
    navList: [],
    activeId: 0,
    videoList: [],
    videoId: "",
    videoUpdateTime: [],
    isTrigger: false
  },
  onLoad(options) {
    this.getNavList()

  },
  toSearch() {
    wx.navigateTo({
      url: '/pages/search/search',
    })
  },
  handleToLower() {
    console.log("到底了");
  },
  handleRefresh() {
    this.getVideoList(this.data.activeId)
  },
  handleEnd(e) {
    let {
      videoUpdateTime
    } = this.data
    videoUpdateTime.splice(videoUpdateTime.findIndex(item => item.vid === e.currentTarget.id), 1)
    this.setData({
      videoUpdateTime
    })
  },
  handleTimeUpdate(e) {
    let videoTimeObj = {
      vid: e.currentTarget.id,
      currentTime: e.detail.currentTime
    }
    let {
      videoUpdateTime
    } = this.data
    let videoItem = videoUpdateTime.find(item => item.vid == videoTimeObj.vid)
    if (videoItem) {
      videoItem.currentTime = e.detail.currentTime
    } else {
      videoUpdateTime.push(videoTimeObj)
    }
    this.setData({
      videoUpdateTime
    })
  },
  handlePlay(e) {
    let vid = e.currentTarget.id
    this.vid !== vid && this.videoContext && this.videoContext.stop()
    this.vid = vid
    this.setData({
      videoId: vid
    })
    this.videoContext = wx.createVideoContext(vid)
    let {
      videoUpdateTime
    } = this.data
    let videoItem = videoUpdateTime.find(item => item.vid === vid)
    if (videoItem) {
      this.videoContext.seek(videoItem.currentTime)
    }
    this.videoContext.play()
  },
  async getNavList() {
    try {
      let res = await request("video/group/list", {})
      this.setData({
        navList: res.data.slice(0, 14),
        activeId: res.data[0].id
      })
      this.getVideoList(this.data.activeId)
    } catch (error) {
      console.log(error);
    }

  },
  async getVideoList(navId) {
    wx.showLoading({
      title: '加载中',
    })
    try {
      let res = await request("video/group", {
        id: navId
      })
      if (res.code === 200) {
        this.setData({
          videoList: res.datas,
          isTrigger: false
        })
        wx.hideLoading()
      } else {
        wx.hideLoading()
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    } catch (error) {
      console.log(error);
    }

  },
  changeNav(e) {
    let activeId = e.currentTarget.id
    this.setData({
      videoList: [],
      activeId: activeId * 1
    })

    this.getVideoList(activeId)
  },
  onShareAppMessage() {},
  onShareTimeline() {}
})